<template>
    <!-- 碎片管理抽屉 -->
    <el-drawer v-model="isDrawerVisible" title="碎片管理 (Multipart)" direction="rtl" size="60%" @open="handleDrawerOpen"
        :before-close="handleBeforeClose">
        <div class="fragment-container">
            <!-- 1. 操作栏 -->
            <div class="action-bar">
                <div>
                    <el-button type="primary" @click="handleDeleteSelected"
                        :disabled="!selectedFragments.length || isLoading" :loading="isDeleting">
                        删除
                    </el-button>
                    <el-button type="danger" plain @click="handleDeleteAll"
                        :disabled="!fragmentList.length || isLoading" :loading="isDeleting">
                        全部删除
                    </el-button>
                    <el-button :icon="Refresh" @click="fetchFragments" :disabled="isLoading || isDeleting" circle
                        title="刷新" />
                </div>
                <el-input v-model="searchKeyword" placeholder="按文件路径搜索" clearable style="width: 240px"
                    :prefix-icon="Search" />
            </div>

            <!-- 2. 数据表格 -->
            <el-table :data="filteredFragments" v-loading="isLoading" stripe style="width: 100%; margin-top: 16px;"
                height="calc(100vh - 180px)" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="key" label="文件路径" sortable show-overflow-tooltip />
                <el-table-column prop="uploadId" label="Upload ID" width="300" show-overflow-tooltip />
                <el-table-column prop="initiated" label="生成时间" width="200" sortable>
                    <template #default="{ row }">
                        {{ formatDateTime(row.initiated) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="100" align="center">
                    <template #default="{ row }">
                        <el-button type="danger" link @click="handleDeleteSingle(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </el-drawer>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Refresh, Search } from '@element-plus/icons-vue';
import apiClient from '@/api';
import { formatDateTime } from '@/utils/formatters.js';

// --- Props & Emits ---
const props = defineProps({
    bucketName: {
        type: String,
        required: true,
    },
    visible: {
        type: Boolean,
        default: false,
    },
});

const emit = defineEmits(['update:visible']);

// --- Drawer Visibility ---
const isDrawerVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value),
});

const handleBeforeClose = (done) => {
    if (isDeleting.value) {
        ElMessage.warning('正在删除中，请稍后...');
        return;
    }
    done();
};


// --- State ---
const isLoading = ref(false);
const isDeleting = ref(false);
const fragmentList = ref([]);
const selectedFragments = ref([]);
const searchKeyword = ref('');

// --- Computed ---
const filteredFragments = computed(() => {
    if (!searchKeyword.value) {
        return fragmentList.value;
    }
    return fragmentList.value.filter(fragment =>
        fragment.key.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
});

// --- API Calls ---
const fetchFragments = async () => {
    if (!props.bucketName) return;
    isLoading.value = true;
    try {
        const response = await apiClient.get(`/api/v1/buckets/${props.bucketName}/multipart-uploads`);
        fragmentList.value = response.data;
    } catch (error) {
        console.error("获取碎片列表失败:", error);
        ElMessage.error(error.response?.data?.error || '获取碎片列表失败');
    } finally {
        isLoading.value = false;
    }
};

defineExpose({
    // 将 fetchFragments 方法暴露出去，父组件可以通过 ref 调用它
    fetchFragments,
});

const deleteFragments = async (fragmentsToDelete, confirmationMessage) => {
    if (!fragmentsToDelete.length) return;

    try {
        await ElMessageBox.confirm(confirmationMessage, '确认操作', {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning',
        });
    } catch {
        return; // 用户点击了取消
    }

    isDeleting.value = true;
    try {
        const payload = {
            uploads: fragmentsToDelete.map(f => ({ key: f.key, uploadId: f.uploadId })),
        };
        const response = await apiClient.delete(`/api/v1/buckets/${props.bucketName}/multipart-uploads`, { data: payload });

        ElMessage.success(response.data.message || '清理成功');
        if (response.data.errors && response.data.errors.length > 0) {
            ElMessage.warning(`有 ${response.data.errors.length} 个项目清理失败。`);
            console.warn('部分清理失败详情:', response.data.errors);
        }

        // 清理成功后刷新列表
        await fetchFragments();

    } catch (error) {
        console.error("删除碎片失败:", error);
        ElMessage.error(error.response?.data?.error || '删除碎片失败');
    } finally {
        isDeleting.value = false;
    }
};

// --- Event Handlers ---
const handleDrawerOpen = () => {
    fetchFragments();
};

const handleSelectionChange = (selection) => {
    selectedFragments.value = selection;
};

const handleDeleteSingle = (row) => {
    deleteFragments([row], `确定要删除文件 "${row.key}" 对应的这个碎片任务吗？此操作不可恢复。`);
};

const handleDeleteSelected = () => {
    deleteFragments(selectedFragments.value, `确定要删除选中的 ${selectedFragments.value.length} 个碎片任务吗？此操作不可恢复。`);
};

const handleDeleteAll = () => {
    deleteFragments(fragmentList.value, `确定要删除当前存储桶内所有的 ${fragmentList.value.length} 个碎片任务吗？这是一个高危操作，请谨慎确认！`);
};
</script>

<style scoped>
.fragment-container {
    padding: 0 20px;
    display: flex;
    flex-direction: column;
    height: 100%;
}

.action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0;
}
</style>